import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Notification } from 'element-ui'
// import ca from 'element-ui/src/locale/lang/ca'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 8000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    return response.data
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          Notification.error({ title: error.response.data.message || 'Error', duration: 5000 })
          break
        case 401:
          Notification.error({ title: '未授权，请重新登录', duration: 5000 })
          break
        case 403:
          Notification.error({ title: '拒绝访问', duration: 5000 })
          break
        case 404:
          Notification.error({ title: '请求错误,未找到该资源', duration: 5000 })
          break
        case 405:
          Notification.error({ title: '请求方法未允许', duration: 5000 })
          break
        case 408:
          Notification.error({ title: '请求超时', duration: 5000 })
          break
        case 500:
          Notification.error({ title: '服务器端出错', duration: 5000 })
          break
        case 501:
          Notification.error({ title: '网络未实现', duration: 5000 })
          break
        case 502:
          Notification.error({ title: '网络错误', duration: 5000 })
          break
        case 503:
          Notification.error({ title: '服务不可用', duration: 5000 })
          break
        case 504:
          Notification.error({ title: '网络超时', duration: 5000 })
          break
        case 505:
          Notification.error({ title: 'http版本不支持该请求', duration: 5000 })
          break
        default:
          Notification.error({ title: `未知错误${error.response.status}`, duration: 5000 })
      }
    } else {
      Notification.error({ title: '连接到服务器失败', duration: 5000 })
    }
    return Promise.reject(error)
  }
)

export default service
